import { DeleteOutlined, EditOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons'

import { Button, Card, Cascader, Drawer, Form, Input, message, Popconfirm, Table, Tag } from 'antd'
import { Store } from 'rc-field-form/lib/interface'
import React, { useEffect, useState } from 'react'
import '../../DepartmentManage/views/style.css'
import TableToolbar from '../../../components/TableSetting/TableToolbar'
import { fetchRequest } from '../../../utils/Request'
import { url } from '../../../utils/url'
import { useDispatch, useSelector } from 'react-redux'
import actionType from '../actionType'
import { useRequest, useUnmount } from '@umijs/hooks'
import AddEquipment from "./AddEquipment";
import ModifyEquipment from "./ModifyEquipment";


interface RequestParams {
    index: number,
    num: number,
    devName: string,
    devLocation: string,
    level: number,
    addrArray: string[]
}

interface RequestAddress {
    level: number,
    parentID: string,
    addrArray: string[]
}

interface DevSelect {
    targetKeys: string[],
    selectedKeys: string[],
}

interface ModifyParams {
    deptID: string,
    devList: string[]
}

interface DetailInfo {
    visible: boolean,
    content: any
}

export default function EquipmentTable() {

    //
    const devInfo = useSelector((state: any) => {
        return state.equipment;
    })
    const [sechData, setsechData] = useState({
        index: 0,
        num: 10,
        level: 0,
        devName: "",
        devLocation: "",
        addrArray: [""],
        deviceCode: ''

    })
    const columns = [
        {
            title: '设备编码',
            dataIndex: 'deviceCode',
            key: 'deviceCode',
        }, {
            title: '设备名称',
            dataIndex: 'devName',
            key: 'devName'
        }, {
            title: "设备地址",
            dataIndex: "allAddress",
            key: "allAddress",
        },
        //  {
        //     title: "设备状态",
        //     dataIndex: "state",
        //     key: "state"
        // },
        {
            title: "位置描述",
            dataIndex: "devLocation",
            key: 'devLocation',
        }, {
            title: "设备类型",
            dataIndex: "deviceModel",
            key: 'deviceModel'
        },
        {
            title: "状态",
            dataIndex: "terminalState",
            render: (record: any) => {
                return record === 1 ? <Tag color="#3ae0b0">在线</Tag> : record === 2 ? <Tag color="#f50">离线</Tag> :
                    <Tag color="#2db7f5">未知</Tag>;
            }
        }
        , {
            title: "操作", key: "opeartion",
            render: (record: any) =>
                <small>
                    <Tag className="tags-hover" color="#108ee9" icon={<EditOutlined />}
                        onClick={() => setmodifyVisible({ visible: true, content: record })}>编辑</Tag>
                    <Popconfirm
                        title="确定要删除？"
                        onConfirm={async (e: any) => {

                            await deleteDev.run({
                                deviceID: record.deviceID
                            })
                        }}>
                        <Tag className="tags-hover delete" color="#f50" icon={<DeleteOutlined />}>删除</Tag>
                    </Popconfirm>
                    <Popconfirm
                        title="确定要激活？"
                        onConfirm={(e: any) => {
                            getTableData.run({ deviceCode: record.deviceCode })
                        }}>
                        <Tag className="tags-hover enable" style={{ display: record.healthMode ? '' : 'none' }}
                            color="#8fd224" icon={<EditOutlined />}>激活</Tag>
                    </Popconfirm>
                    <span style={{ display: record.greenCodeState ? '' : 'none' }}>
                        <span style={{ display: 'inline-block', width: '160px' }}>
                            <Popconfirm
                                title="确定要防疫核验开？"
                                onConfirm={(e: any) => {
                                    getControl.run({
                                        deviceCode: record.deviceCode, status: 0
                                    })
                                }}>
                                <Tag className={record.greenCodeState === '0' ? 'health' : 'healthNoT'}
                                    style={{ marginRight: '-1px' }}>防疫核验开</Tag>
                            </Popconfirm>
                            <Popconfirm
                                title="确定要防疫核验关？"
                                onConfirm={(e: any) => {
                                    getControl.run({
                                        deviceCode: record.deviceCode, status: 1
                                    })
                                }}>
                                <Tag className={record.greenCodeState === '1' ? 'health' : 'healthNoT'}
                                    style={{}}>防疫核验关</Tag>
                            </Popconfirm>
                        </span>
                    </span>

                    {/* <Tag className="tags-hover" style={{display:record.healthMode?'':'none'}} color="#108ee9" icon={<EditOutlined />} onClick={() => getControl.run({deviceCode:record.deviceCode,status:1})}>开关</Tag> */}

                </small>
        }
    ]

    const [form] = Form.useForm()

    //点击搜索按钮

    function handleFinish(values: Store) {
        setsechData({
            addrArray: typeof values.allAddress === "undefined" ? [""] : values.allAddress,
            devName: typeof values.devName === "undefined" ? "" : values.devName,
            devLocation: typeof values.devLocation === "undefined" ? "" : values.devLocation,
            level: typeof values.allAddress === "undefined" ? 0 : values.allAddress.length,
            index: 0,
            num: 10,
            deviceCode: values?.deviceCode ?? ''
        })
        dispatch({
            type: actionType.SET_EQUIPMENT_PARAMS,
            payload: {
                addrArray: typeof values.allAddress === "undefined" ? [""] : values.allAddress,
                devName: typeof values.devName === "undefined" ? "" : values.devName,
                devLocation: typeof values.devLocation === "undefined" ? "" : values.devLocation,
                level: typeof values.allAddress === "undefined" ? 0 : values.allAddress.length,
                index: 0,
                len: 10,
                deviceCode: values?.deviceCode ?? ''
            }
        })
    }

    //  激活方法
    const activate = async (params: any) => {
        try {
            const json = await fetchRequest(url.GET_ACTIVATE, params);
            if (json.success) {
                getDevTable.run(sechData)
                // dispatch({ type: actionType.SET_EQUIPMENT_PARAMS, payload: { index: 0, len: 10, level: 0, devName: "", devLocation: "", addrArray: [""] } })
                message.success(json.message)
            } else {
                message.error(json.message || json.result)
            }
        } catch (error: any) {
            message.error(error.message)
        }
    }
    // 发送表格数据请求传参
    const getTableData = useRequest(activate, {
        manual: true,
        loadingDelay: 200
    })
    // 防疫核验开关接口
    const control = async (params: any) => {
        try {
            const json = await fetchRequest(url.GET_CONTROL, params);
            if (json.success) {
                getDevTable.run(sechData)
            } else {
                message.error(json.message || json.result)
            }
        } catch (error: any) {
            message.error(error.message)
        }
    }

    // 发送防疫核验开关
    const getControl = useRequest(control, {
        manual: true,
        loadingDelay: 200
    })

    //点击重置按钮
    function handleReset() {
        // console.log(values)
        form.resetFields();
        dispatch({
            type: actionType.SET_EQUIPMENT_PARAMS,
            payload: { index: 0, len: 10, level: 0, devName: "", devLocation: "", addrArray: [""] }
        })
        //TODO 后续请求数据
    }

    const [requestAddress, setRequestAddress] = useState<any>({ "level": 0, "parentID": "", "addrArray": [''] })
    const [addressNode, setAddressNode] = useState([])

    async function getAllAddressNode(params: RequestAddress) {
        try {
            const json = await fetchRequest(url.GET_ALL_ADDRESS_NODE, params);
            if (json.success) {
                // console.log('getAllAddressNode:',json)
                setAddressNode(json.data)
                // return json.data
            } else {
                // console.log('getAllAddressNode:',json)
                // return []
            }
        } catch (error: any) {
            // console.log('getAllAddressNode:',error)
        }
    }

    const getAllAddress = useRequest(getAllAddressNode, {
        manual: true,
        loadingDelay: 200
    })


    async function getAllAdd(params: RequestAddress) {
        try {
            const json = await fetchRequest(url.GET_ALL_ADDRESS_NODE, params);
            if (json.success) {
                // console.log('getAllAdd:',json)
                return json.data
            } else {
                // console.log('getAllAdd:',json)
                return []
            }
        } catch (error: any) {
            // console.log('error:',error)
        }
    }

    useEffect(() => {
        getAllAddress.run(requestAddress)
    }, [])

    const OnChange = (value: any, selectedOptions: any) => {
        // console.log('selectedOptions',selectedOptions);

    };

    const loadData = (selectedOptions: any) => {
        //
        const targetOption = selectedOptions[selectedOptions.length - 1];

        targetOption.loading = true;

        let jsondata: any = [];

        let addrArray: any = [];

        selectedOptions.forEach(function (item: any) {
            addrArray.push(item['value'])
        })

        getAllAdd({
            "level": targetOption['level'] + 1,
            "parentID": targetOption['value'],
            "addrArray": addrArray
        }).then((e: any) => {
            jsondata = e

        })

        setTimeout(() => {
            targetOption.loading = false;

            // if (jsondata.length==0 && selectedOptions.length==1){
            //     targetOption.disabled = true;
            //     targetOption.isLeaf = true;
            // }

            targetOption.children = jsondata;
            console.log(targetOption)
            setAddressNode([...addressNode])
        }, 1000);
    };

    // function options(value:any){
    //     value.map((item:any)=>{
    //         if (item.isLeaf==true){
    //             item.disabled = true
    //         }
    //         return item
    //     })
    //     // console.log(value)
    //     return value
    // }
    function filter(inputValue: string, path: any[]) {
        return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }

    //查询框
    const searchForm = (
        <Card className="search-form">
            <Form form={form} layout="inline" initialValues={{ deptState: "1" }}
                onFinish={handleFinish} onReset={handleReset}>

                {/*<Form.Item className="form-control-item" name="orzName" label="学校&#160;&#160;&#160;&#160;&#160;&#160;&#160;">*/}
                {/*    <Input className="search-form-item" />*/}
                {/*</Form.Item>*/}

                <Form.Item className="form-control-item" name="allAddress" label="设备地址">

                    <Cascader
                        placeholder="请输入设备地址"
                        options={addressNode}
                        loadData={loadData}
                        showSearch={{ filter }}
                        style={{ width: 200 }}
                        changeOnSelect
                        onChange={OnChange}
                    />
                </Form.Item>

                <Form.Item className="form-control-item" name="deviceCode" label="设备编号">
                    <Input className="search-form-item" />
                </Form.Item>


                <Form.Item className="form-control-item" name="devName" label="设备名称">
                    <Input className="search-form-item" />
                </Form.Item>

                <Form.Item className="form-control-item" name="devLocation" label="位置描述">
                    <Input className="search-form-item" />
                </Form.Item>

                {/* <Form.Item className="form-control-item" name="devLocation" label="设备位置">
            <Input className="search-form-item" />
        </Form.Item> */}


                <Form.Item className="form-control-item">
                    <Button type="primary" icon={<SearchOutlined />} htmlType="submit"
                        style={{ marginRight: '8px' }}>搜索</Button>
                    <Button icon={<SyncOutlined />} htmlType="reset">重置</Button>

                </Form.Item>

            </Form></Card>)

    const [columnsKey, setcolumnsKey] = useState<any[]>([])

    const [realColumns, setrealColumns] = useState<any[]>([])

    const [devList, setdevList] = useState<DevSelect>({
        targetKeys: [],
        selectedKeys: []
    })

    const [modifyVisible, setmodifyVisible] = useState<DetailInfo>({ visible: false, content: null })

    const [manageList, setmanageList] = useState<any[]>([])

    const [addVisible, setaddVisible] = useState<boolean>(false)


    //点击刷新按钮
    function onRefresh() {
        // getDept.run()
        getDevTable.run(devInfo.requestParams)
    }

    //点击新增按钮
    function onAdd() {
        setaddVisible(true)
    }

    function onColumnsChange(checkedList: any[]) {
        setcolumnsKey(checkedList)
    }


    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        // console.log('realColumns',realColumns)
        setrealColumns(realColumns)
    }, [ columnsKey])


    const dispatch = useDispatch()


    //得到信息
    async function getEquipmentTable(params: RequestParams) {
        try {
            const json = await fetchRequest(url.GET_EQUIPMENT, params);
            if (json.success) {
                dispatch({ type: actionType.GET_EQUIPMENT, payload: { data: json.data, count: json.count } })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getDevTable = useRequest(getEquipmentTable, {
        manual: true,
        loadingDelay: 200
    })


    //
    useEffect(() => {
        // getDevTable.run(devInfo.requestParams);
        getDevTable.run(sechData)

    }, [devInfo.requestParams])


    //删除设备的接口
    async function deleteDevRequest(params: { deviceID: string }) {

        try {
            const json = await fetchRequest(url.DELETE_ENTRANCE, params);
            if (json.success) {
                message.destroy();
                message.success("删除成功！");
                getDevTable.run(devInfo.requestParams)
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }


    const deleteDev = useRequest(deleteDevRequest, {
        manual: true,
        loadingDelay: 200
    })

    //点击分页的时候
    function handlePageChange(page: number) {
        setsechData({ ...sechData, index: (page - 1) * 10 })
        dispatch({ type: actionType.SET_EQUIPMENT_PARAMS, payload: { index: (page - 1) * 10 } })
    }

    //新增成功
    function addSuccess() {
        // message.destroy();
        // message.success("新增成功!");
        setaddVisible(false);
        getDevTable.run(devInfo.requestParams)
    }

    function onModifySuccess() {
        setmodifyVisible({ visible: false, content: modifyVisible.content });
        getDevTable.run(devInfo.requestParams)
    }


    useUnmount(() => {
        dispatch({
            type: actionType.SET_EQUIPMENT_PARAMS, payload: {
                devName: "",
                devLocation: "",
                addrArray: [""]
            }
        })
    })

    function setDataDevTableList(DataDevTableList: any) {
        return DataDevTableList.map((item: any, index: any) => {
            // console.log(item)
            let itemString: any = ''
            if (item['building'] == null) {
                itemString =
                    item['collegeName'] + '-' +
                    item['collegeAreaName']
            } else if (item['building'] != null && item['unit'] == null) {
                itemString =
                    item['collegeName'] + '-' +
                    item['collegeAreaName'] + '-' +
                    item['building'] + '栋'
            } else {
                itemString =
                    item['collegeName'] + '-' +
                    item['collegeAreaName'] + '-' +
                    item['building'] + '栋-' +
                    item['unit'] + '单元';
            }

            return { ...item, 'allAddress': itemString }
        })
    }


    return (
        <div>
            {searchForm}
            <Card className="search-form-table">
                <TableToolbar buttonText="新增" tableName="设备清单" columns={columns} onColumnsChange={onColumnsChange}
                    onRefresh={onRefresh} onAdd={onAdd} />
                <Table
                    rowKey={(record: any) => record.deviceCode}
                    pagination={{
                        hideOnSinglePage: true,
                        simple: true,
                        onChange: handlePageChange,
                        total: devInfo.devTableList.count,
                        current: devInfo.requestParams.index / 10 + 1,
                        pageSize: 10,
                        showSizeChanger: false
                    }}
                    loading={getDevTable.loading}
                    columns={realColumns}
                    dataSource={setDataDevTableList(devInfo.devTableList.data)} />
            </Card>
            <Drawer width="800PX" destroyOnClose visible={addVisible} title="新增设备" onClose={() => setaddVisible(false)}>
                <AddEquipment addSuccess={addSuccess} />
            </Drawer>

            <Drawer width="800px" visible={modifyVisible.visible} title="修改信息" destroyOnClose
                onClose={() => setmodifyVisible({ content: modifyVisible.content, visible: false })}>
                <ModifyEquipment content={modifyVisible.content} onModifySuccess={onModifySuccess} />
            </Drawer>

        </div>
    )

}
